package com.zhonglz.system.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhonglz.commons.base.BaseController;
import com.zhonglz.model.SysLog;
import com.zhonglz.model.SysUser;
import com.zhonglz.util.result.ResultUtils;
import com.zhonglz.util.tools.DataGrid;
import com.zhonglz.util.tools.VerifyCode;


/***
 * 系统用户信息表
 * @author xiaozhong
 *
 */
@RestController
@RequestMapping("/sys/user")
public class UserController extends BaseController {
	
	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	/****
	 * 用户名密码登陆
	 * @param username 用户名
	 * @param password 密码
	 * @param usercode 验证码
	 * @param randomCode 请求码
	 * @return
	 */
	@ResponseBody
    @RequestMapping("/login")
	public ResultUtils login(String username,String password ,String usercode,String randomCode) {
		//1.校验验证码 先根据请求码去rides查询到验证码，再根据查询出来的验证码与前端传递过来的验证码做比对
		String randomValues = (String) redisTemplate.opsForValue().get(randomCode);
		if(!randomValues.equals(usercode)){
			return new ResultUtils(ResultUtils.CODE_ERROR_PARAM,"请输入正确的验证码！");
		}
		//2.去数据库查询是否有该用户
		ResultUtils result= sysUserService.login(username,password);
		return result;
	}
	
	
//	@ResponseBody
//    @RequestMapping("/login")
//	public ResultUtils login(@RequestBody LoginUserMain loginUserMain) {
//		//1.校验验证码 先根据请求码去rides查询到验证码，再根据查询出来的验证码与前端传递过来的验证码做比对
//		String randomValues = (String) redisTemplate.opsForValue().get(loginUserMain.getRandomCode());
//		if(!randomValues.equals(loginUserMain.getUserCode())){
//			return new ResultUtils(ResultUtils.CODE_ERROR_PARAM,"请输入正确的验证码！");
//		}
//		//2.去数据库查询是否有该用户
//		ResultUtils result= sysUserService.login(loginUserMain.getUsername(),loginUserMain.getPassword());
//		return result;
//	}
	
	/****
	 * 根据随机码生成一张验证码
	 * @param response
	 * @param request
	 * @param randomCode 前端请求码随机码
	 */
	@GetMapping("/getVerifyCode")
	public void getVerificationCode(HttpServletResponse response, HttpServletRequest request,String randomCode) {
		try {
			int width = 130;
			int height = 30;
			BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			//生成对应宽高的初始图片
			String randomText = VerifyCode.drawRandomText(width, height, verifyImg);
			logger.info("验证码:"+randomText+"\t请求码随机码："+randomCode);
			try {
				//先删除redis中的值
				redisUtils.deleteKey(randomCode);
				//redis的String存值
                redisTemplate.opsForValue().set(randomCode, randomText);
                //验证码3分钟过期
                redisUtils.expireKey(randomCode, 180, TimeUnit.SECONDS);
			}catch(Exception e){
				e.printStackTrace();
				logger.info("存储失败,redis存储错误:"+e.getMessage());
			}
			response.setContentType("image/png");// 必须设置响应内容类型为图片，否则前台不识别
			OutputStream os = response.getOutputStream(); // 获取文件输出流
			ImageIO.write(verifyImg, "png", os);// 输出图片流
			os.flush();
			os.close();// 关闭流
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	/**
     * getUserData  分页查询系统用户列表
     * @param sysUser 系统用户实体
     * @param pageNumber 页数
     * @param limit 每页显示多少条数据
     * @return
     */
	@ResponseBody
    @RequestMapping("selectListByData")
    public DataGrid getUserData(SysLog sysLog,
    		@RequestParam(defaultValue="") String startTime,
    		@RequestParam(defaultValue="") String endTime,
    		@RequestParam(defaultValue = "1") int pageNumber,
			@RequestParam(defaultValue = "10") int pageSize,
			HttpServletRequest req) {
    	DataGrid dataGrid = null;
		try {
			// 封装查询条件参数
			Map<String, Object> mapParam = new HashMap<String, Object>();
			if(!startTime.equals("")&&startTime!=null){
				startTime+=" 00:00:00";
				mapParam.put("startTime",startTime);
			}
			if(!endTime.equals("")&&endTime!=null){
				endTime+=" 23:59:59";
				mapParam.put("endTime",endTime);
			}
			PageHelper.startPage(pageNumber, pageSize);
			List<SysUser> selectUserList=sysUserService.getUserData(mapParam);
			PageInfo<SysUser> info = new PageInfo<SysUser>(selectUserList);
			// 封装结果集
			dataGrid = new DataGrid(info.getTotal(),selectUserList,info.getPages(),info.getPageNum(),ResultUtils.CODE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return dataGrid;
    }

	/***
	 * 保存用户信息
	 * @param sysUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveUserInfo")
	public ResultUtils saveUserInfo(SysUser sysUser){
		return sysUserService.saveUserInfo(sysUser);
	}



}
